import axios from "axios";
import { Message, MessageBox } from "element-ui";
import store from "../store";
import { getToken } from "@/utils/auth";

// 创建axios实例
const service = axios.create({
  withCredentials: true,
  timeout: 5000 // 请求超时时间
});

// request拦截器
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers["token"] = getToken(); // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// response 拦截器
service.interceptors.response.use(
  response => {
    const { date } = response.headers; //以服务器响应时间为准
    store.commit("UPDATE_DATE", date || new Date());
    if (response.data.code == "401") {
      store.commit("SET_TOKEN", {
        token: ""
      });

      // store.commit("UPDATE_LOGIN", {});

      // store.commit("UPDATE_USER_INFO", {});

      // store.commit("UPDATE_LOGOUT");

      store.dispatch("FedLogOut").then(() => {
        location.reload(); // 为了重新实例化vue-router对象 避免bug
      });

      // 需要登录页面弹窗
      // if (router.currentRoute.meta.requireAuth) {
      //   store.commit('UPDATE_LOGIN_POPUP')
      // }
    }
    if (!response.data.success) {
      if (response.data.code != "401" && response.data.message) {
        Message.error(response.data.message);
      }
    }
    return response;
  },
  error => {
    let msg = error.message || "网络繁忙，请稍后再试";
    if (msg.indexOf("timeout") > -1) {
      msg = "网络繁忙，请稍后再试";
    }
    Message.error(msg);
    return Promise.reject(error);
  }
);

export default service;

/**
 * 封装get方法
 * @param url
 * @param params
 * @returns {Promise<any>}
 */

export function get(url, params = {}) {
  return new Promise((resolve, reject) => {
    service
      .get(url, {
        params: params
      })
      .then(response => {
        if (response.data.success) {
          return resolve(response.data);
        } else {
          return reject(response.data);
        }
      })
      .catch(err => {
        reject(err);
      });
  });
}

/**
 * 封装post请求
 * @param url
 * @param data
 * @param options
 * @returns {Promise}
 */

export function post(url, data = {}, options) {
  return new Promise((resolve, reject) => {
    service.post(url, data, options).then(
      response => {
        if (response.data.success) {
          return resolve(response.data.result);
        } else {
          return reject(response.data);
        }
      },
      err => {
        reject(err);
      }
    );
  });
}
